const express = require('express');
const router = express.Router();
const SubscriptionCohortStatsService = require('./subscriptionCohortStatsService.js');
const { executeDailyCohortTask } = require('./dailyCohortTask.js');

/**
 * 配置产品周期参数
 * POST /api/cohort/config/product
 * Body: {
 *   product_id: 'weekly_premium_with_1week_offer',
 *   pk: 'com.seamobitech.whatsscanwebclone', 
 *   cycle_days: 7,
 *   cycle_unit: 'week',
 *   window_days: 2,
 *   trial_days: 7,
 *   remark: '首周优惠'
 * }
 */
router.post('/config/product', async (req, res) => {
    try {
        // 单个参数显式提取
        const product_id = req.body.product_id;
        const pk = req.body.pk;
        const cycle_days = req.body.cycle_days;
        const cycle_unit = req.body.cycle_unit;
        const window_days = req.body.window_days;
        const trial_days = req.body.trial_days;
        const remark = req.body.remark;

        // 校验必填字段
        if (!product_id || !pk) {
            return res.status(400).json({
                success: false,
                message: '缺少必填字段: product_id 和 pk'
            });
        }

        // 合成配置，设置默认值
        const productConfig = {
            product_id: product_id,
            pk: pk,
            cycle_days: typeof cycle_days !== 'undefined' ? cycle_days : 7,
            cycle_unit: cycle_unit || 'week',
            window_days: typeof window_days !== 'undefined' ? window_days : 1,
            trial_days: typeof trial_days !== 'undefined' ? trial_days : 0,
            remark: remark || ''
        };

        // 1. 保存产品配置
        const cohortSrv = new SubscriptionCohortStatsService();
        await cohortSrv.upsertProductConfig(productConfig);

        // 2. 自动触发补全本产品历史 cohort
        // max_terms 可固定也可通过 req.body 传递，这里写死 6
        await cohortSrv.repairSingleProduct(pk, product_id, 99999);

        // 3. 返回成功
        res.json({
            success: true,
            message: `产品配置保存成功，并已自动补全该产品历史数据: ${productConfig.product_id}`,
            data: productConfig
        });

    } catch (error) {
        console.error('保存产品配置或自动补全失败:', error);
        res.status(500).json({
            success: false,
            message: '保存产品配置或历史补全失败',
            error: error.message
        });
    }
});


/**
 * 获取所有产品配置列表
 * GET /api/cohort/config/products
 */
router.get('/config/products', async (req, res) => {
    try {
        const cohortSrv = new SubscriptionCohortStatsService();
        const configs = await cohortSrv.getAllProductConfigs();

        res.json({
            success: true,
            data: configs,
            total: configs.length
        });

    } catch (error) {
        console.error('获取产品配置失败:', error);
        res.status(500).json({
            success: false,
            message: '获取产品配置失败',
            error: error.message
        });
    }
});

/**
 * 删除产品配置
 * DELETE /api/cohort/config/product/:productId/:pk
 */
router.delete('/config/product/:productId/:pk', async (req, res) => {
    try {
        const { productId, pk } = req.params;

        const cohortSrv = new SubscriptionCohortStatsService();
        await cohortSrv.deleteProductConfig(productId, pk);

        res.json({
            success: true,
            message: `产品配置删除成功: ${productId} (${pk})`
        });

    } catch (error) {
        console.error('删除产品配置失败:', error);
        res.status(500).json({
            success: false,
            message: '删除产品配置失败',
            error: error.message
        });
    }
});

/**
 * 执行单个产品的历史数据补全
 * POST /api/cohort/repair/single
 * Body: {
 *   product_id: 'weekly_premium_with_1week_offer',
 *   pk: 'com.seamobitech.whatsscanwebclone',
 *   max_terms: 6  // 可选，默认6期
 * }
 */
router.post('/repair/single', async (req, res) => {
    try {
        const { product_id, pk, max_terms = 6 } = req.body;

        if (!product_id || !pk) {
            return res.status(400).json({
                success: false,
                message: '缺少必填字段: product_id 和 pk'
            });
        }

        console.log(`开始执行单个产品历史补全: ${pk}#${product_id}`);
        const startTime = Date.now();

        const cohortSrv = new SubscriptionCohortStatsService();
        await cohortSrv.repairSingleProduct(pk, product_id, max_terms);

        const duration = (Date.now() - startTime) / 1000;
        const message = `产品 ${product_id} 历史数据补全完成，耗时: ${duration}秒`;

        console.log(message);
        res.json({
            success: true,
            message,
            data: {
                product_id,
                pk,
                max_terms,
                duration_seconds: duration
            }
        });

    } catch (error) {
        console.error('历史数据补全失败:', error);
        res.status(500).json({
            success: false,
            message: '历史数据补全失败',
            error: error.message
        });
    }
});

/**
 * 执行所有已配置产品的历史数据补全
 * POST /api/cohort/repair/all
 * Body: {
 *   max_terms: 6  // 可选，默认6期
 * }
 */
router.post('/repair/all', async (req, res) => {
    try {
        const { max_terms = 6 } = req.body;

        console.log('开始执行全部产品历史补全...');
        const startTime = Date.now();

        const cohortSrv = new SubscriptionCohortStatsService();

        // 获取所有配置的产品
        const productConfigs = await cohortSrv.getAllProductConfigs();

        if (productConfigs.length === 0) {
            return res.json({
                success: true,
                message: '没有找到任何产品配置，无需补全',
                data: {
                    processed_products: 0,
                    duration_seconds: 0
                }
            });
        }

        // 按包名分组执行
        const pkGroups = {};
        productConfigs.forEach(config => {
            if (!pkGroups[config.pk]) {
                pkGroups[config.pk] = [];
            }
            pkGroups[config.pk].push(config);
        });

        let totalProcessed = 0;
        for (const [pk, configs] of Object.entries(pkGroups)) {
            console.log(`处理包: ${pk}, 包含 ${configs.length} 个产品`);
            await cohortSrv.repairAllHistory([pk], max_terms);
            totalProcessed += configs.length;
        }

        const duration = (Date.now() - startTime) / 1000;
        const message = `全部产品历史数据补全完成，共处理 ${totalProcessed} 个产品，耗时: ${duration}秒`;

        console.log(message);
        res.json({
            success: true,
            message,
            data: {
                processed_products: totalProcessed,
                max_terms,
                duration_seconds: duration
            }
        });

    } catch (error) {
        console.error('全部历史数据补全失败:', error);
        res.status(500).json({
            success: false,
            message: '全部历史数据补全失败',
            error: error.message
        });
    }
});

/**
 * 手动执行一次每日统计任务
 * POST /api/cohort/task/daily
 */
router.post('/task/daily', async (req, res) => {
    try {
        console.log('手动触发每日统计任务...');
        const startTime = Date.now();

        await executeDailyCohortTask();

        const duration = (Date.now() - startTime) / 1000;
        const message = `每日统计任务执行完成，耗时: ${duration}秒`;

        console.log(message);
        res.json({
            success: true,
            message,
            data: {
                duration_seconds: duration
            }
        });

    } catch (error) {
        console.error('每日统计任务执行失败:', error);
        res.status(500).json({
            success: false,
            message: '每日统计任务执行失败',
            error: error.message
        });
    }
});

/**
 * 获取cohort统计报告
 * GET /api/cohort/report
 * Query: pk, product_id, start_date, end_date
 */
router.get('/report', async (req, res) => {
    try {
        const { pk, product_id, start_date, end_date } = req.query;

        if (!pk || !product_id || !start_date || !end_date) {
            return res.status(400).json({
                success: false,
                message: '缺少必填查询参数: pk, product_id, start_date, end_date'
            });
        }

        const cohortSrv = new SubscriptionCohortStatsService();
        const report = await cohortSrv.getCohortReport(pk, product_id, start_date, end_date);

        res.json({
            success: true,
            data: report,
            total: report.length,
            params: { pk, product_id, start_date, end_date }
        });

    } catch (error) {
        console.error('获取cohort报告失败:', error);
        res.status(500).json({
            success: false,
            message: '获取cohort报告失败',
            error: error.message
        });
    }
});

/**
 * 获取产品续订率趋势分析
 * GET /api/cohort/analysis/trend
 * Query: pk, product_id, days (可选，默认30)
 */
router.get('/analysis/trend', async (req, res) => {
    try {
        const { pk, product_id, days = 30 } = req.query;

        if (!pk || !product_id) {
            return res.status(400).json({
                success: false,
                message: '缺少必填查询参数: pk, product_id'
            });
        }

        const cohortSrv = new SubscriptionCohortStatsService();
        const analysis = await cohortSrv.getTrendAnalysis(pk, product_id, parseInt(days));

        res.json({
            success: true,
            data: analysis,
            params: { pk, product_id, days: parseInt(days) }
        });

    } catch (error) {
        console.error('获取趋势分析失败:', error);
        res.status(500).json({
            success: false,
            message: '获取趋势分析失败',
            error: error.message
        });
    }
});

module.exports = router;